package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.TotalWork;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.service.TotalWorkService;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/totalWork")
public class TotalWorkController {
    @Autowired
    private TotalWorkService totalWorkService;
    @Autowired
    private UserService userService;

    @GetMapping("/totalWorkList")
    public ResponseEntity<Map<String, Object>> totalWorkList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<TotalWork> page = new Page<>(currentPage, pageSize);
            QueryWrapper<TotalWork> queryWrapper = new QueryWrapper<>();

            // 添加年度查询条件
            String totalWorkYear = params.get("totalWorkYear");
            if (StringUtils.isNotBlank(totalWorkYear)) {
                queryWrapper.eq("total_work_year", totalWorkYear);
            }

            // 调用service层的方法，直接获取带用户名的数据
            IPage<TotalWork> resultPage = totalWorkService.getAdminTotalWorkListWithUserInfo(page, queryWrapper, params.get("userKeyword"));
            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords()); // 当前页数据（包含用户名）
            response.put("total", resultPage.getTotal()); // 总记录数
            System.out.println("总记录数="+resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent()); // 当前页码
            response.put("pageSize", resultPage.getSize()); // 每页大小
            response.put("totalPages", resultPage.getPages()); // 总页数

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 导入用户表格数据
     * @param file
     * @return
     */
    @PostMapping("/importTotalWork")
    public ResponseEntity<Map<String, Object>> importTotalWork(@RequestParam("file") MultipartFile file) {
        try {
            totalWorkService.importData(file);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "数据导入成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "数据导入失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 增加
     * @param totalWork
     * @return
     */
    @PostMapping("/addTotalWork")
    public ResponseEntity<Map<String, Object>> addUser(@RequestBody TotalWork totalWork) {
        System.out.println("==" + totalWork);
        String username = totalWork.getUsername(); // 从前端获取的用户名
        if (username == null || username.isEmpty()) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        // 根据用户名获取用户信息
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }

        String userId = user.getUserId();

        // 判断该用户是否已经在 total_work 表中存在记录
        QueryWrapper<TotalWork> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        int count = totalWorkService.count(queryWrapper);

        if (count > 0) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("msg", "该用户已存在，不能重复新增");
            return ResponseEntity.badRequest().body(response);
        }

        // 设置 userId 并保存
        totalWork.setUserId(userId);
        totalWorkService.save(totalWork);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "新增成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 删除
     * @param totalWorkIds
     * @return
     */
    @DeleteMapping("/deleteTotalWork")
    public ResponseEntity<Map<String, Object>> deleteUser(@RequestBody List<Long> totalWorkIds) {
        System.out.println("删除：" + totalWorkIds);
        totalWorkService.removeByIds(totalWorkIds);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改
     * @param totalWork
     * @return
     */
    @PutMapping("/editTotalWork")
    public ResponseEntity<Map<String, Object>> editUser(@RequestBody TotalWork totalWork) {
        System.out.println("user::" + totalWork);
        totalWorkService.updateById(totalWork);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    @GetMapping("/export")
    public void exportTotalWork(
        @RequestParam(required = false) String totalWorkYear,
        HttpServletResponse response) throws IOException {
//        System.out.println("控制器层 - 开始导出，年度参数：" + totalWorkYear);
        totalWorkService.exportTotalWork(totalWorkYear, response);
    }
}
